package com.example.mvvmtest.view

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.mvvmtest.R
import com.example.mvvmtest.databinding.ActivityMainBinding
import com.example.mvvmtest.model.database.UserDatabase
import com.example.mvvmtest.Repository.UserRepository
import com.example.mvvmtest.viewModel.MainActivityViewModel

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private lateinit var userId: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        // 获取登录账号
        userId = intent.getStringExtra("USER_ID") ?: run {
            finish()  // 没有账号信息则返回登录页
            return
        }

        // 初始化数据绑定
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        // 初始化ViewModel
        val dao = UserDatabase.getDatabase(application).userDao()
        val repository = UserRepository(dao)
        val viewModel = ViewModelProvider(this, object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                if (modelClass.isAssignableFrom(MainActivityViewModel::class.java)) {
                    return MainActivityViewModel(userId, repository) as T
                }
                throw IllegalArgumentException("Unknown ViewModel class")
            }
        })[MainActivityViewModel::class.java]

        // 绑定ViewModel
        binding.viewModel = viewModel
        binding.lifecycleOwner = this
        binding.updateBtn.setOnClickListener {
            // 从输入框获取数据（处理空安全）
            val newPassword = binding.newPassword.text?.toString() ?: ""
            val newAge = binding.newAge.text?.toString() ?: ""
            val newJob = binding.newJob.text?.toString() ?: ""

            // 调用ViewModel的方法
            viewModel.updateInfo(newPassword, newAge, newJob)
        }


        // 观察加载状态，控制按钮是否可用
        viewModel.isLoading.observe(this) { isLoading ->
            binding.updateBtn.isEnabled = !isLoading // 加载中禁用按钮
        }
    }
}